package com.ranyk.www.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ranyk.www.constant.UserReturnCode;
import com.ranyk.www.entity.AdminUser;
import com.ranyk.www.entity.AdminUserLoginLog;
import com.ranyk.www.entity.Role;
import com.ranyk.www.entity.UserRole;
import com.ranyk.www.enums.StatusEnum;
import com.ranyk.www.exception.ValidateException;
import com.ranyk.www.mapper.AdminUserLoginLogMapper;
import com.ranyk.www.mapper.AdminUserMapper;
import com.ranyk.www.mapper.UserRoleMapper;
import com.ranyk.www.pojo.dto.AdminUserPageDTO;
import com.ranyk.www.pojo.vo.AdminUserVO;
import com.ranyk.www.service.IAdminUserService;
import com.ranyk.www.support.page.PageInfo;
import com.ranyk.www.util.PasswordUtils;
import com.ranyk.www.util.UserUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * CLASS_NAME: UserServiceImpl.java <br/>
 *
 * @author ranyk           <br/>
 * @version V1.0           <br/>
 * @decription: 管理员表 业务逻辑层接口实现  <br/>
 * @date: 2022-04-03 <br/>
 */
@Service("adminUserService")
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    private AdminUserMapper adminUserMapper;
    private AdminUserLoginLogMapper adminUserLoginLogMapper;
    private UserRoleMapper userRoleMapper;

    @Autowired
    public void setUserMapper(AdminUserMapper adminUserMapper) {
        this.adminUserMapper = adminUserMapper;
    }

    @Autowired
    public void setUserLoginLogMapper(AdminUserLoginLogMapper adminUserLoginLogMapper) {
        this.adminUserLoginLogMapper = adminUserLoginLogMapper;
    }

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public Integer insertUser(AdminUser user, String[] roleIds, String userName) throws ValidateException {
        // 验证用户名
        if (this.checkLoginName(user.getLoginName())) {
            throw new ValidateException(UserReturnCode.ACCOUNT_ERROR);
        }
        // 插入该管理员
        user.setSalt(PasswordUtils.getSalt());
        user.setLoginPassword(PasswordUtils.getMd5(user.getLoginPassword(), user.getLoginName(), user.getSalt()));
        user.setPicImg(UserUtils.getPicImg());
        user.setCreateBy(userName);
        user.setCreateTime(new Date());
        user.setUpdateBy(userName);
        user.setUpdateTime(new Date());
        Integer count = adminUserMapper.insert(user);
        // 插入角色列表
        return batchInsertUserRole(user, roleIds, userName, count);
    }

    @Override
    public AdminUser getByLoginName(String loginName) {
        AdminUser user = new AdminUser();
        user.setLoginName(loginName);
        return adminUserMapper.selectOne(new QueryWrapper<>(user));
    }

    @Override
    public AdminUserVO getById(Long userId) {
        return adminUserMapper.getById(userId);
    }

    @Override
    public List<AdminUserVO> listByUser(AdminUserVO userVo) {
        return adminUserMapper.listByUser(userVo);
    }

    @Override
    public AdminUserPageDTO listByPage(PageInfo pageInfo, String search) {
        Page<AdminUserVO> page = new Page<>(pageInfo.getCurrent(), pageInfo.getLimit());
        RowBounds rowBounds = new RowBounds(pageInfo.getCurrent(), pageInfo.getLimit());
        List<AdminUserVO> userVOList = adminUserMapper.listByPage(pageInfo, search, rowBounds);
        pageInfo.setTotal(Long.valueOf(page.getTotal()).intValue());
        return new AdminUserPageDTO(userVOList, pageInfo);
    }

    @Override
    public List<AdminUserVO> listByOrganizationId(Long organizationId) {
        // TODO 对该sql语句进行整合
        // 通过组织ID查找管理员
        AdminUserVO userVO = new AdminUserVO();
        userVO.setOrganizationId(organizationId);
        List<AdminUserVO> userVOList = adminUserMapper.listByUser(userVO);
        // 对管理员列表进行遍历,获取角色信息
        for (AdminUserVO vo : userVOList) {
            List<Role> roles = userRoleMapper.listByUserId(vo.getUserId(), StatusEnum.NORMAL.getStatus());
            vo.setRoles(roles);
        }
        return userVOList;
    }

    @Override
    public AdminUserPageDTO listByOrganizationId(Long organizationId, PageInfo pageInfo, String search) {
        Page<AdminUserVO> page = new Page<>(pageInfo.getCurrent(), pageInfo.getLimit());
        RowBounds rowBounds = new RowBounds(pageInfo.getCurrent(), pageInfo.getLimit());
        List<AdminUserVO> userVOList = adminUserMapper.listByOrganizationId(organizationId, pageInfo, search, rowBounds);
        pageInfo.setTotal(Long.valueOf(page.getTotal()).intValue());
        return new AdminUserPageDTO(userVOList, pageInfo);
    }

    @Override
    public Integer updateLogById(Long userId, AdminUserLoginLog userLoginLog) {

        // 创建用户登录日志
        adminUserLoginLogMapper.insert(userLoginLog);

        // 更新User表用户登录信息
        AdminUser user = new AdminUser();
        user.setUserId(userId);
        user.setLastLoginTime(new Date());
        user.setLastLoginIp(userLoginLog.getUserIp());
        return adminUserMapper.updateById(user);
    }

    /**
     * 更新管理员信息
     *
     * @param user 管理员信息
     * @return 返回更新后影响的行数
     */
    @Override
    public Integer updateByUserId(AdminUser user) {
        user.setUpdateTime(new Date());
        return adminUserMapper.updateById(user);
    }

    @Override
    public Integer updateUser(AdminUser user, String[] roleIds, String userName) {
        // 更新用户信息
        user.setUpdateTime(new Date());
        user.setUpdateBy(userName);
        Integer count = adminUserMapper.updateById(user);

        // 删除UserRole 表用户记录
        UserRole userRoleById = new UserRole();
        userRoleById.setUserId(user.getUserId());
        userRoleMapper.delete(new QueryWrapper<>(userRoleById));

        // 插入SystemUserLoginLog 表用户记录
        return batchInsertUserRole(user, roleIds, userName, count);
    }

    private Integer batchInsertUserRole(AdminUser user, String[] roleIds, String userName, Integer count) {
        if (roleIds != null && roleIds.length > 0) {
            List<UserRole> userRoles = new ArrayList<>();
            for (String roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setCreateTime(new Date());
                userRole.setRoleId(Long.valueOf(roleId));
                userRole.setCreateBy(userName);
                userRoles.add(userRole);
            }
            // 插入角色列表
            userRoleMapper.insertUserRoles(userRoles);
        }
        return count;
    }

    @Override
    public Integer updatePsw(String nowPassword, String newPassword, Long userId, String userName)
            throws ValidateException {
        AdminUser user = adminUserMapper.selectById(userId);

        String password = PasswordUtils.getMd5(nowPassword, user.getLoginName(), user.getSalt());
        if (user.getLoginPassword() == null || !user.getLoginPassword().equals(password)) {
            throw new ValidateException(UserReturnCode.WRONG_PASSWORD);
        }

        AdminUser updateUser = new AdminUser();
        updateUser.setUserId(userId);
        updateUser.setUpdateBy(userName);
        updateUser.setUpdateTime(new Date());
        updateUser.setLoginPassword(PasswordUtils.getMd5(newPassword, user.getLoginName(), user.getSalt()));
        return adminUserMapper.updateById(updateUser);
    }

    @Override
    public Integer updateStatus(Long userId) {
        AdminUser user = adminUserMapper.selectById(userId);
        if (user != null && StatusEnum.NORMAL.getStatus().equals(user.getStatus())) {
            AdminUser updateUser = new AdminUser();
            updateUser.setUserId(userId);
            updateUser.setStatus(StatusEnum.FREEZE.getStatus());
            return adminUserMapper.updateById(updateUser);
        } else if (user != null && StatusEnum.FREEZE.getStatus().equals(user.getStatus())) {
            AdminUser updateUser = new AdminUser();
            updateUser.setUserId(userId);
            updateUser.setStatus(StatusEnum.NORMAL.getStatus());
            return adminUserMapper.updateById(updateUser);
        }
        return null;
    }

    @Override
    public Integer deleteByUserId(Long userId) {

        // 删除管理员登录记录
        AdminUserLoginLog loginLog = new AdminUserLoginLog();
        loginLog.setUserId(userId);
        adminUserLoginLogMapper.delete(new UpdateWrapper<>(loginLog));

        // 删除管理员角色记录
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRoleMapper.delete(new UpdateWrapper<>(userRole));

        // 删除管理员信息
        return adminUserMapper.deleteById(userId);
    }


    /**
     * 获取管理员信息,含用户信息和用户角色信息
     *
     * @param userId 需要查询管理员的用户ID
     * @return 获取到的用户信息和用户角色信息, 存放在 Map&lt;String, Object&gt; 集合中
     */
    @Override
    public Map<String, Object> getAdminInfo(Long userId) {
        Map<String, Object> result = new HashMap<>(3);
        // 管理员用户信息
        AdminUserVO userVO = adminUserMapper.getById(userId);
        result.put("user", userVO);
        // 管理员角色
        List<Role> roles = userRoleMapper.listByUserId(userId, StatusEnum.NORMAL.getStatus());
        result.put("roles", roles);
        return result;
    }

    private boolean checkLoginName(String loginName) {
        AdminUser user = new AdminUser();
        user.setLoginName(loginName);
        int count = adminUserMapper.selectCount(new QueryWrapper<>(user)).intValue();
        return count > 0;
    }

    @Override
    public Integer updateAvatar(Long userId, String picImg) {
        AdminUser user = new AdminUser();
        user.setUserId(userId);
        user.setPicImg(picImg);
        user.setUpdateTime(new Date());
        return adminUserMapper.updateById(user);
    }
}
